import { ref } from 'vue'
import { authAPI } from '@/api'
import { ElMessage } from 'element-plus'

// 用户状态
export const user = ref(null)
export const isLoggedIn = ref(false)
export const loading = ref(false)

// 登录方法
export async function login(username, password) {
  loading.value = true
  try {
    const response = await authAPI.login(username, password)
    
    if (response.success) {
      // 保存用户信息和token
      user.value = response.user
      isLoggedIn.value = true
      localStorage.setItem('user', JSON.stringify(response.user))
      localStorage.setItem('token', response.token)
      
      ElMessage.success(response.message || '登录成功')
      return { success: true, user: response.user }
    } else {
      ElMessage.error(response.message || '登录失败')
      return { success: false, message: response.message }
    }
  } catch (error) {
    console.error('Login error:', error)
    const errorMessage = error.response?.data?.message || error.response?.data?.detail || '登录失败，请重试'
    ElMessage.error(errorMessage)
    return { success: false, message: errorMessage }
  } finally {
    loading.value = false
  }
}

// 登出方法
export async function logout() {
  loading.value = true
  
  // 立即清除本地状态，提升用户体验
  user.value = null
  isLoggedIn.value = false
  localStorage.removeItem('user')
  localStorage.removeItem('token')
  loading.value = false
  ElMessage.success('已退出登录')
  
  // 后台异步调用登出接口，即使失败也不影响前端状态
  try {
    // 使用Promise.race添加3秒超时，避免长时间等待
    await Promise.race([
      authAPI.logout(),
      new Promise((_, reject) => 
        setTimeout(() => reject(new Error('Logout timeout')), 3000)
      )
    ])
  } catch (error) {
    console.warn('Backend logout failed (this is okay):', error)
    // 后端登出失败不影响前端，因为本地状态已清除
  }
}

// 获取当前用户信息
export async function getCurrentUser() {
  const token = localStorage.getItem('token')
  if (!token) {
    return null
  }
  
  try {
    const userInfo = await authAPI.getCurrentUser()
    user.value = userInfo
    isLoggedIn.value = true
    localStorage.setItem('user', JSON.stringify(userInfo))
    return userInfo
  } catch (error) {
    console.error('Get current user error:', error)
    // token可能已过期，清除本地状态
    user.value = null
    isLoggedIn.value = false
    localStorage.removeItem('user')
    localStorage.removeItem('token')
    return null
  }
}

// 刷新token
export async function refreshToken() {
  try {
    const response = await authAPI.refreshToken()
    if (response.success && response.token) {
      localStorage.setItem('token', response.token)
      return true
    }
    return false
  } catch (error) {
    console.error('Refresh token error:', error)
    return false
  }
}

// 初始化用户状态
export async function initAuth() {
  // 避免重复初始化
  if (loading.value) {
    return
  }
  
  const savedUser = localStorage.getItem('user')
  const token = localStorage.getItem('token')
  
  if (savedUser && token) {
    try {
      // 先设置本地缓存的用户状态，快速响应
      user.value = JSON.parse(savedUser)
      isLoggedIn.value = true
      
      // 异步验证token是否有效，不阻塞界面显示
      setTimeout(async () => {
        try {
          await getCurrentUser()
        } catch (error) {
          console.error('Token验证失败:', error)
          // 如果验证失败，清除本地状态
          user.value = null
          isLoggedIn.value = false
          localStorage.removeItem('user')
          localStorage.removeItem('token')
        }
      }, 500) // 延迟500ms验证，确保界面已经渲染
      
    } catch (error) {
      console.error('Init auth error:', error)
      // 如果本地数据解析失败，清除本地状态
      user.value = null
      isLoggedIn.value = false
      localStorage.removeItem('user')
      localStorage.removeItem('token')
    }
  }
} 